#!coding:utf8
'''
Created on Aug 7, 2012

@author: join
'''
from lottery_jx.common import tools, utils
from lottery_jx.models import Account,SystemSettings
#from PIL import ImageColor, ImageFont, ImageDraw
#import random
#import Image
#import md5
import datetime
#import StringIO
#from django.http import HttpResponse
#import os
#import cStringIO

@tools.render
def index(request):
    
    return 'login.html'

@tools.ajaxrender
def login(request):
    '''登录后台管理系统，可以用额度账户，也可以用登录名，记录登录者信息到session.'''
    
    username = request.POST.get('username',None)
    password = request.POST.get('password',None)
    
    if not username or not password:
        return u'用户名密码不能为空',400
    
#    accounts = Account.objects.filter(account=username,deleted=False)
#    if not accounts:
    accounts = Account.objects.filter(loginname=username,deleted=False)
    
    if not accounts:
        return u'用户名不存在',400
    
    if len(accounts)>1:
        return u'您的用户名有重名，请联系管理员',500
    
    account = accounts[0]
    if account.password == tools.getMD5Str(password):
        request.session['user'] = accounts[0]
        request.session['lastlogintime'] = utils.convert_datetime_to_str(account.logintime, "%Y-%m-%d %H:%M:%S")
        account.logintime = datetime.datetime.now()
        account.loginip = request.META['REMOTE_ADDR']
        account.save()
        return u'登录成功',200
    else:
        return u'用户名密码不匹配',400
    
@tools.render
def home(req):
    '''主页'''

    accounts = Account.objects.filter(id=req.session['user'].id,deleted=False)
    settings = SystemSettings.objects.filter(deleted=False).all()

    if accounts[0].accountType==0:
        act = 'alarm_shop'
    elif accounts[0].accountType==2:
        act = 'alarm_tianfu'
    elif accounts[0].accountType==1:
        act = 'null'
    if settings:
        if act != 'null':
            for setting in settings:      
                if str(act) == str(setting.itemname):
                    setting_value = setting.itemvalue
                
                else:
                    pass
        else:
            setting_value = 'null'     
    if  setting_value == 'null':
        return 'index.html',{'loginname':accounts[0].loginname,'accountType':accounts[0].accountType,'account':accounts[0].account,'balance':float(accounts[0].balance),'lastlogintime':req.session['lastlogintime'],'setting_value':setting_value}
    else:
        return 'index.html',{'loginname':accounts[0].loginname,'accountType':accounts[0].accountType,'account':accounts[0].account,'balance':float(accounts[0].balance),'lastlogintime':req.session['lastlogintime'],'setting_value':float(setting_value)}
   
@tools.render
def rehome12(request):
    '''关闭阀值提示'''
    accounts = Account.objects.filter(id=request.session['user'].id,deleted=False)
    return 'index.html',{'loginname':accounts[0].loginname,'accountType':accounts[0].accountType,'account':accounts[0].account,'balance':float(accounts[0].balance),'lastlogintime':request.session['lastlogintime'],'setting_value':float(0.0)}



@tools.render
def logout(req):
    '''安全退出系统，清空session信息'''
    if req.session.has_key('user'):
        del req.session['user']
        del req.session['lastlogintime']
    return 'login.html'
    

#def get_check_code_image(request):
#    imagepath = os.path.join(os.path.dirname(os.path.dirname(__file__)),'static','images','checkcode.gif')
#    im = Image.open(imagepath)
#    string = {'number':'12345679',
#              'litter':'ACEFGHKMNPRTUVWXY'}
#    background = (random.randrange(230,255),random.randrange(230,255),random.randrange(230,255))
#    line_color = (random.randrange(0,255),random.randrange(0,255),random.randrange(0,255))
#    img_width = 58
#    img_height = 30 
#    font_color = ['black','darkblue','darkred']
#    font_size = 14
#    font = ImageFont.truetype('msyh.ttf',font_size)
#    request.session['verify'] = ''
# 
#    #新建画布
#    im = Image.new('RGB',(img_width,img_height),background)
#    code = random.sample(string['litter'],4)
#    #code  = u'和谐社会'
#    #新建画笔
#    draw = ImageDraw.Draw(im)
# 
#    #画干扰线
#    for i in range(random.randrange(3,5)):
#        xy = (random.randrange(0,img_width),random.randrange(0,img_height),
#              random.randrange(0,img_width),random.randrange(0,img_height))
#        draw.line(xy,fill=line_color,width=1)
#     
#    #写入验证码文字
#    x = 2
#    for i in code:
#        y = random.randrange(0,10)
#        draw.text((x,y), i, font=font, fill=random.choice(font_color))
#        x += 14
#        request.session['verify'] += i
#    del x
#     
#    del draw
#    buf = StringIO()
#    im.save(buf,'gif')
#    buf.seek(0)
#    return HttpResponse(buf.getvalue(),'image/gif')


#def get_check_code_image(request):
#    imagepath = os.path.join(os.path.dirname(os.path.dirname(__file__)),'static','images','checkcode.gif')
#    im = Image.open(imagepath)      
#    draw = ImageDraw.Draw(im)      
#    mp = md5.new()      
#    mp_src = mp.update(str(datetime.datetime.now()))      
#    mp_src = mp.hexdigest()      
#    rand_str = mp_src[0:4]         
#    draw.text((10,10), rand_str[0], font=ImageFont.truetype("ARIAL.TTF", random.randrange(25,50)))      
#    draw.text((48,10), rand_str[1], font=ImageFont.truetype("ARIAL.TTF", random.randrange(25,50)))      
#    draw.text((85,10), rand_str[2], font=ImageFont.truetype("ARIAL.TTF", random.randrange(25,50)))      
#    draw.text((120,10), rand_str[3], font=ImageFont.truetype("ARIAL.TTF", random.randrange(25,50)))      
#    del draw      
#    request.session['checkcode'] = rand_str      
#    buf = cStringIO.StringIO()      
#    im.save(buf, 'gif')
#    return HttpResponse(buf.getvalue(),'image/gif')   